package com.forlove.app.common.base.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.event.BaseMessageEvent;
import com.forlove.app.common.base.mvp.presenter.IBasePresenter;
import com.forlove.app.common.base.mvp.view.BaseView;
import com.forlove.app.common.utils.CommonUtil;
import com.forlove.app.common.utils.SystemUtils;
import com.forlove.app.event.EventEntity;
import com.forlove.app.manager.NetworkManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;

import butterknife.ButterKnife;

import static android.os.Looper.getMainLooper;

/**
 * Created by yx on 2017/6/2.
 */

public abstract class BaseFragment<T extends IBasePresenter> extends Fragment implements BaseView {

    public abstract int getLayoutId();

    private View mRootView;
    protected Activity mContext;
    protected T presenter;
    protected boolean isInit = false;//判断view是否进行create和destroy，不影响变量的初始化和引用
//    private YimeiToast yimeiToast;
//
//    private YimeiLoadingDialog loadingDialog;

    protected void setPresenter(T presenter) {
        this.presenter = presenter;
    }

//    @Override
//    public void onSaveInstanceState(Bundle outState) {
//        //super.onSaveInstanceState(outState);
//    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        WeakReference<Activity> weakReference = new WeakReference<>(activity);
        mContext = weakReference.get();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    /**
     * 隐藏toolbar的原生的title
     */
    public void showToolBar(final BaseActivity baseActivity, Toolbar toolbar, boolean showBack) {
        if (toolbar == null && !(baseActivity instanceof BaseActivity)) {
            return;
        }

        baseActivity.setSupportActionBar(toolbar);
        ActionBar actionBar = baseActivity.getSupportActionBar();
        if (showBack) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            toolbar.setNavigationIcon(R.mipmap.tab_backarrow_gray);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    baseActivity.onBackPressed();
                }
            });
        } else {
            //设置是否显示navigation
            actionBar.setDisplayHomeAsUpEnabled(false);
            toolbar.setNavigationIcon(null);
            toolbar.setNavigationOnClickListener(null);
        }

        if (actionBar != null) {
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    /**
     * 显示右边的icon和点击事件
     */
    public void showToolBar(final BaseActivity baseActivity, Toolbar toolbar, int navigationIconID,
                            View.OnClickListener onClickListener, Toolbar.OnMenuItemClickListener onMenuItemClickListener) {
        if (toolbar == null && !(baseActivity instanceof BaseActivity)) {
            return;
        }

        baseActivity.setSupportActionBar(toolbar);
        ActionBar actionBar = baseActivity.getSupportActionBar();
        if (navigationIconID > 0) {
            actionBar.setDisplayHomeAsUpEnabled(true);

            toolbar.setOnMenuItemClickListener(onMenuItemClickListener);
            toolbar.setNavigationIcon(navigationIconID);
            toolbar.setNavigationOnClickListener(onClickListener);

        } else {
            //设置是否显示navigation
            actionBar.setDisplayHomeAsUpEnabled(false);
            toolbar.setNavigationIcon(null);
            toolbar.setNavigationOnClickListener(null);
        }

        if (actionBar != null) {
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(getLayoutId(), container, false);
            //绑定fragment
            ButterKnife.bind(this, mRootView);
        }
        initFragmentView();
        return mRootView;
    }

    protected View getRootView() {
        return mRootView;
    }

    protected void initFragmentView() {

    }

    public void onSelected(int pos) {

    }

    protected void runOnUiThread(Runnable action) {
        if (mContext == null) {
            throw new NullPointerException("mContext is null");
        }
        mContext.runOnUiThread(action);
    }

    public static BaseFragment getClassFromName(String name) {
        try {
            BaseFragment fragment = (BaseFragment) Class.forName(name).newInstance();
            return fragment;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static BaseFragment newInstance(String fragmentName, Bundle bundle) {

        BaseFragment fragment = getClassFromName(fragmentName);
        if (bundle != null) {
            fragment.setArguments(bundle);
        }

        return fragment;
    }

    @Override
    public void onPause() {
        super.onPause();
        //LogUtil.e("yjl", getClass().getSimpleName() + "   onPause()  ");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit = false;
        //清除rootview
        if (mRootView != null) {
            ((ViewGroup) mRootView.getParent()).removeView(mRootView);
        }
        //LogUtil.e("yjl", getClass().getSimpleName() + "   onDestroyView()  ");
    }

    @Override
    public void onDestroy() {
        isInit = false;
        // LogUtil.e("yjl", getClass().getSimpleName() + "   onDestroy()  ");
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
//        if (yimeiToast != null) {
//            yimeiToast.dismiss();
//            yimeiToast = null;
//        }
//        if (loadingDialog != null) {
//            loadingDialog.dismiss();
//            loadingDialog = null;
//        }
        mContext = null;
        mRootView = null;
        super.onDestroy();
    }

    /**
     * 必须使用标记符。这表明要在UI线程中处理
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false)
    public synchronized void onEventMainThread(final BaseMessageEvent event) {
//        LogUtil.e(getClass().getSimpleName() + " onEventMainThread:" + event.eventId);
//        if (event != null && event.eventId == 10003) {
//            toLoginActivity();
////            LogUtil.e("yjl", getClass().getSimpleName() + " romove event:" + event.eventId);
//            EventBus.getDefault().removeStickyEvent(event);
//        }
//        if (event != null && event.getEventName().equals("event_fail_toast")) {
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    showToast("网络开小差了~~");
//                    hideLoadingView();
//                }
//            });
//        }
//        if (event != null && event.eventId == 10008) {
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    if (event.getEventName() != null) {
//                        showToast(event.getEventName());
//                    }
//                    hideLoadingView();
//                }
//            });
//        }
    }

    /**
     * 必须使用标记符。这表明要在与发布线程相同的线程中处理
     */
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = false)
    public void onEvent(EventEntity eventEntity) {
    }

    /**
     * 必须使用标记符。这表明如果是在UI线程中发布，则在新线程中运行
     */
    @Subscribe(threadMode = ThreadMode.BACKGROUND, sticky = false)
    public void onEventBackgroundThread(BaseMessageEvent event) {

    }

    /**
     * 必须使用标记符。在新线程中运行
     */
    @Subscribe(threadMode = ThreadMode.ASYNC, sticky = false)
    public void onEventAsync(BaseMessageEvent event) {

    }


    /**
     * 只展示消息，并自动消失
     *
     * @param msg
     */
    protected void showToast(String msg) {
//        if (mContext != null) {
//            if (yimeiToast == null) {
//                yimeiToast = new YimeiToast(mContext);
//            }
//            yimeiToast.setMsg(msg);
//            yimeiToast.show(true);
//        }
//        ToastUtils.toast(msg);
    }

    /**
     * 展示消息，自动消失
     *
     * @param msg
     * @param success
     */
    protected void showToast(String msg, boolean success) {
        showToast(msg, success, true);
    }

    /**
     * 显示toast
     *
     * @param msg       文字说明
     * @param success   成功状态还是失败状态
     * @param isDismiss 是否自动消失
     */
    protected void showToast(final String msg, final boolean success, final boolean isDismiss) {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (mContext != null) {
//                    if (yimeiToast == null) {
//                        yimeiToast = new YimeiToast(mContext);
//                    }
//                    yimeiToast.setMsg(msg);
//                    yimeiToast.setMsg(msg, success);
//                    yimeiToast.show(isDismiss);
//                }
//            }
//        });

    }

    @Override
    public void showLoadingView() {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (mContext != null) {
//                    //显示加载view
//                    if (loadingDialog == null) {
//                        loadingDialog = new YimeiLoadingDialog(mContext);
//                    }
//                    loadingDialog.setDialogCancelable(false);
//                    loadingDialog.show(false);
//                    Handler handler = new Handler(getMainLooper());
//                    handler.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            loadingDialog.dismiss();
//                        }
//                    }, 6 * 1000);
//                }
//            }
//        });

    }

    @Override
    public void hideLoadingView() {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (loadingDialog != null && loadingDialog.isShowing()) {
//                    loadingDialog.dismiss();
//                }
//            }
//        });
        Handler handler = new Handler(getMainLooper());
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                if (loadingDialog != null && loadingDialog.isShowing()) {
//                    loadingDialog.dismiss();
//                }
//            }
//        }, 1000);
    }

    //跳转至登录页面
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    protected void onEventToLogin(BaseMessageEvent event) {
//        if (event != null && event.eventId == 10003) {
//            toLoginActivity();
//        }
//    }

    @Override
    public void toLoginActivity() {

        if (SystemUtils.getTopActivity().contains("ChoiceAgeActivity")
                || SystemUtils.getTopActivity().contains("LoginInputPhoneActivity")) {
            return;
        }
        try {
            Intent intent = new Intent();
            intent.setClass(mContext, Class.forName("com.forlove.app.qselect.login.ui.ChoiceAgeActivity"));
            //intent.setClass(mContext, Class.forName("com.yimei.app.activity.register.ui.LoginActivity"));
            //LogUtil.e("yjl", getClass().getSimpleName() + "====" + SystemUtils.getTopActivity());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    showToast("请先登录!");
                }
            });
            toActivity(intent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //show short toast 方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 快捷显示short toast方法，需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
     *
     * @param stringResId
     */
    public void showShortToast(int stringResId) {
        CommonUtil.showShortToast(mContext, stringResId);
    }

    /**
     * 快捷显示short toast方法，需要long toast就用 Toast.makeText(string, Toast.LENGTH_LONG).show(); ---不常用所以这个类里不写
     *
     * @param string
     */
    public void showShortToast(String string) {
        CommonUtil.showShortToast(mContext, string);
    }
    //show short toast 方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //启动新Activity方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 打开新的Activity，向左滑入效果
     *
     * @param intent
     */
    public void toActivity(final Intent intent) {
        CommonUtil.toActivity(mContext, intent);
    }

    /**
     * 打开新的Activity
     *
     * @param intent
     * @param showAnimation
     */
    public void toActivity(final Intent intent, final boolean showAnimation) {
        CommonUtil.toActivity(mContext, intent, showAnimation);
    }

    /**
     * 打开新的Activity，向左滑入效果
     *
     * @param intent
     * @param requestCode
     */
    public void toActivity(final Intent intent, final int requestCode) {
        CommonUtil.toActivity(mContext, intent, requestCode);
    }

    /**
     * 打开新的Activity
     *
     * @param intent
     * @param requestCode
     * @param showAnimation
     */
    public void toActivity(final Intent intent, final int requestCode, final boolean showAnimation) {
        CommonUtil.toActivity(mContext, intent, requestCode, showAnimation);
    }
    //启动新Activity方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    /**
     * 只是跳转的main activity
     * 不做子页面切换
     */
    protected void toMainActivity() {
        toMainActivity(-1, -1);
    }

    /**
     * 跳转main activity的某个子页面
     *
     * @param pos
     */
    protected void toMainActivity(int pos) {
        toMainActivity(pos, -1);
    }

    /**
     * 跳转main activity
     * 可以切换子页面和 子页面的二级页面
     *
     * @param pos       子页面
     * @param childView 子页面的二级页面
     */
    protected synchronized void toMainActivity(int pos, int childView) {
        try {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            if (pos >= 0) {
                bundle.putInt("pos", pos);
            }
            if (childView >= 0) {
                bundle.putInt("childView", childView);
            }
            intent.putExtras(bundle);
            intent.setClass(mContext, Class.forName("com.yimei.app.activity.MainActivity"));
            toActivity(intent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }
}
